package com.aaa.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author 郎老师
 * @company AAA软件教育
 * @title ${NAME}
 * @date 2019/9/23 18:37
 */
@WebServlet(name = "BaseServlet")
public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数, 用来识别用户想请求的方法
        String methodName = request.getParameter("method");

        // 判断该参数是否存在, 不存在,抛出异常
        if(methodName == null || methodName.trim().isEmpty()){
            throw new RuntimeException("您没有传递 method 参数! 无法确定您想调用的方法");
        }

        // 得到当前类的 class 对象
        Class c = this.getClass();

        // 查询方法, 参数需要: 方法名和该方法的参数类型
        // 该方法的参数类型必须与 service 中的参数类型一致
        Method method = null;
        try{
            method = c.getMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
        } catch(Exception e){
            throw new RuntimeException("您要调用的方法"+methodName+",它不存在!");
        }

        // 调用 method 方法
        // 反射调用, 第一参数表示当前类,
        // 正常调用: this.method(req,resp)
        try{
            method.invoke(this,request,response);
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
